<template>
  <div class="home-container">
    <navbar @performSearch="performSearch" />
    <main class="content">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <ul v-else class="product-list">
        <li v-for="item in items" :key="item.id" class="product-item" :style="{ 'flex-basis': columnWidth }">
          <div class="product-image">
            <img v-if="item.image" :src="item.image" :alt="item.itemName" style="width: 100px; height: 100px;">
          </div>
          <h3>{{ item.itemName }}</h3>
          <p>描述: {{ item.description }}</p>
          <p>价格: {{ item.itemPrice }}</p>
          <p>类别: {{ item.category }}</p>
          <div class="quantity-selector">
            <button @click="decreaseQuantity(item)" class="quantity-button">-</button>
            <span>{{ item.quantity }}</span>
            <button @click="increaseQuantity(item)" class="quantity-button">+</button>
          </div>
          <button @click="addToCart(item)">加入购物车</button>
        </li>
      </ul>
    </main>
  </div>
</template>

<script>
import navbar from '@/component/navbar.vue';
import instance from '@/utils/request';

export default {
  name: 'home',
  components: {
    navbar
  },
  computed: {
    columnWidth() {
      const columns = Math.min(this.items.length, 4);
      // return `calc(100% / ${columns} - 2em)`;
      return `calc(25% - 2em)`;
    }
  },
  data() {
    return {
      items: [],
      loading: true,
      error: '',
    };
  },
  mounted() {
    this.fetchItems();
  },
  methods: {
    async fetchItems() {
      this.loading = true;
      try {
        const response = await instance.get('http://8.219.49.219:8080/onlineShopping/item/items'); 
        this.items = response.data.data.map(item => ({ ...item, quantity: 1 }));
      } catch (error) {
        this.error = '无法获得商品信息';
      } finally {
        this.loading = false;
      }
    },
    decreaseQuantity(item) {
      if (item.quantity > 0) {
        item.quantity--;
      }
    },
    increaseQuantity(item) {
      item.quantity++;
    },
    async addToCart(item) {
      if (item.quantity <= 0) {
        alert('数量必须大于0');
        return;
      }

      const requestData = {
        itemName: item.itemName,
        itemPrice: item.itemPrice,
        image: item.image,
        count: item.quantity
      };

      await instance.post('http://8.219.49.219:8080/onlineShopping/shoppingCar/add', requestData)
        .then(response => {
          //console.log('商品添加成功:', response.data.data);
          location.reload();
        })
        .catch(error => {
          //console.error('添加商品失败:', error);
        });
    },
    async performSearch(searchQuery) {
      this.loading = true;
      try {
        const response = await instance.post('http://8.219.49.219:8080/onlineShopping/item/search', 
          { search: searchQuery }
        );
        console.log(response.data.data)
        this.items = response.data.data.map(item => ({ ...item, quantity: 1 }));
      } catch (error) {
        this.error = '搜索失败';
        console.error('Error Search:', error);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.product-list {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.product-item {
  border: 1px solid #e0e0e0;
  margin-bottom: 1em;
  padding: 1em;
  flex-basis: calc(25% - 2em);
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
  margin-right: 1em; 
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.product-image img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.product-name {
  margin-top: 10px;
  font-weight: bold;
}

.product-description {
  margin-top: 5px;
  color: #666;
}

.product-price {
  margin-top: 5px;
  color: #4CAF50;
  font-weight: bold;
}

.product-category {
  margin-top: 5px;
  color: #666;
}

.loading, .error {
  text-align: center;
}

button {
  background-color: #4CAF50; 
  color: white; 
  border: none; 
  border-radius: 5px; 
  padding: 10px 20px; 
  font-size: 16px; 
  cursor: pointer; 
  transition: background-color 0.3s; 
}

button:hover {
  background-color: #45a049; 
}

.product-item:last-child {
  margin-right: 0;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.quantity-selector button.quantity-button {
  background-color: #ddd;
  color: #333;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
  font-size: 12px;
}

.quantity-selector span {
  font-weight: bold;
  margin: 0 5px;
}

.quantity-selector + button { 
  margin-left: auto; 
  margin-top: 10px; 
}
</style>